import { Layout, Form, Menu, Input, Tooltip, Icon, Row, Col, Checkbox, Button, Modal } from 'antd';
import { Link } from "react-router-dom";
import { Captcha } from '../../tools/getCaptcha';


import { Foot } from '../../components/Footer';
const { Header, Content } = Layout;
const confirm = Modal.confirm;

import './index.less';

class UI extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            confirmDirty: false,
            yzm: '',
            canSubmit: false
        };

        this.myCaptcha = this.myCaptcha.bind(this);
        this.hadRead = this.hadRead.bind(this);
        this.regTip = this.regTip.bind(this);
    }

    // 组件加载后更新验证码
    componentDidMount() {
        this.myCaptcha();
    }

    regTip(arr, nickname, password) {
        let userObj = {
            name: nickname,
            pwd: password,
            status: false
        }
        arr.push(userObj);
        // 设置sessionStorage
        window.sessionStorage.setItem("user", JSON.stringify(arr));

        // window.this = this;

        confirm({
            title: '恭喜您, 注册成功!',
            content: '立即进入登录界面?',
            okText: '是',
            cancelText: '否',
            onOk: () => {
                this.props.history.push('/login');
            },
            onCancel() {
                // console.log('Cancel');
            },
        });
    }
    // 点击注册按钮
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                if (values.agreement == false) {
                    this.setState({ canSubmit: true })
                } else {
                    let { nickname, password } = values;
                    // {nickname: "lvonve", password: "111111", confirm: "111111", captcha: "qfhc", agreement: true}
                    // 判断是否已存在
                    // 由于是单页面只存在于当前页面,所以用sessionStorage模拟当前登录的用户
                    let getUserArr = window.sessionStorage.getItem('user');
                    // [{name:'lvonve', pwd:'123456'}]
                    if (getUserArr != null) {
                        getUserArr = JSON.parse(getUserArr);
                        let flag = false;

                        getUserArr.map(item => {
                            if (item.name == nickname) {
                                flag = true;
                                return;
                            }
                        });

                        // 该用户已注册
                        if (flag) {
                            Modal.error({
                                title: '错误提示:',
                                content: '该用户名已存在!',
                            });
                        } else {
                            this.regTip(getUserArr, nickname, password);
                        }
                    } else {
                        let arr = [];
                        this.regTip(arr, nickname, password);
                    }
                }
            }
        });
    }
    //确认密码输入框失去焦点更新confirmDirty
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    }
    //实时两次输入密码是否相同
    compareToFirstPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不相同');
        } else {
            callback();
        }
    }
    // 实时判断输入的密码是否合法
    validateToPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }

        if (value == '' || value == null || /^[0-9a-z_]{6,20}$/ig.test(value) == false) {
            callback('密码需要6-20位且只包含数字字母下划线!');
        } else {
            callback();
        }
    }
    //实时判断验证码是否合法
    validateOfYzm = (rule, value, callback) => {
        let { yzm } = this.state;
        if (value == '' || value == null || yzm.toLowerCase() !== value.toLowerCase()) {
            callback('验证码错误!');
        } else {
            callback();
        }
    }
    //设置动态验证码
    myCaptcha() {
        let yzm = Captcha(4);
        this.setState({ yzm });
    }
    // 获取是否同意协议
    hadRead(e) {
        // 由于form表单的值和state的值不同步,所以这里取巧使用取反操作
        this.setState({ canSubmit: !e.target.checked });
    }

    render() {
        const { getFieldDecorator } = this.props.form;

        // 设置输入表单宽度
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        // 设置同意协议和提交按钮的宽度
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };

        return (
            <div className="register form">
                <Layout>
                    <Header >
                        <div className="logo" />
                        <Menu
                            theme="dark"
                            mode="horizontal"
                            style={{ lineHeight: '64px' }}
                        >
                            <Menu.Item key="1">首页</Menu.Item>
                            <Menu.Item key="2">实体书</Menu.Item>
                            <Menu.Item key="3">电子书</Menu.Item>
                        </Menu>
                        <div className="header-r">
                            <p>欢迎来到必要，请 <Link to="/login">登录</Link> | <Link to="/register">注册</Link></p>
                        </div>
                    </Header>
                    <Content className="reg-form">
                        <Form onSubmit={this.handleSubmit}>
                            <Form.Item
                                {...formItemLayout}
                                label={(
                                    <span>
                                        用户名&nbsp;
                                    <Tooltip title="想怎么称呼您?">
                                            <Icon type="question-circle-o" />
                                        </Tooltip>
                                    </span>
                                )}
                            >
                                {/* getFieldDecorator用于与表单进行双向绑定 */}
                                {getFieldDecorator('nickname', {
                                    rules: [{
                                        required: true,
                                        pattern: new RegExp(/^[0-9a-z_]{4,10}$/ig),
                                        message: '用户名需要4-10位且只包含数字字母下划线!',
                                        whitespace: true
                                    }],
                                })(
                                    <Input />
                                )}
                            </Form.Item>

                            <Form.Item
                                {...formItemLayout}
                                label="密码"
                            >
                                {getFieldDecorator('password', {
                                    rules: [{
                                        required: true, message: ' 请输入密码!',
                                    }, {
                                        // 自定义验证器
                                        validator: this.validateToPassword,
                                    }],
                                })(
                                    <Input type="password" />
                                )}
                            </Form.Item>

                            <Form.Item
                                {...formItemLayout}
                                label="确认密码"
                            >
                                {getFieldDecorator('confirm', {
                                    rules: [{
                                        required: true, message: '请确认密码!',
                                    }, {
                                        validator: this.compareToFirstPassword,
                                    }],
                                })(
                                    <Input type="password" onBlur={this.handleConfirmBlur} />
                                )}
                            </Form.Item>

                            <Form.Item
                                {...formItemLayout}
                                label="验证码"
                            >
                                <Row gutter={6}>
                                    <Col span={17}>
                                        {getFieldDecorator('captcha', {
                                            rules: [{ required: true, message: '请输入验证码!' }, {
                                                validator: this.validateOfYzm,
                                            }],
                                        })(
                                            <Input />
                                        )}
                                    </Col>
                                    <Col span={6}>
                                        <Button className="yzm" onClick={this.myCaptcha}>{this.state.yzm}</Button>
                                    </Col>
                                </Row>
                            </Form.Item>

                            <Form.Item {...tailFormItemLayout}>
                                {getFieldDecorator('agreement', {
                                    valuePropName: 'checked',
                                    initialValue: true
                                })(
                                    <Checkbox autoFocus onChange={this.hadRead}>我已经阅读并同意<a href="javascript:;">《网站协议》</a></Checkbox>
                                )}
                            </Form.Item>

                            <Form.Item {...tailFormItemLayout}>
                                <Button type="primary" htmlType="submit" className="submit" disabled={this.state.canSubmit} >注册</Button>
                            </Form.Item>
                        </Form>
                    </Content>
                    <Foot />
                </Layout>
            </div>
        );
    }
}

export const Register = Form.create({ name: 'register' })(UI);